package com.situ.vivamarket.api.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.situ.vivamarket.model.Goods;
import com.situ.vivamarket.model.search.GoodsSearchBean;
import com.situ.vivamarket.service.CategoryService;
import com.situ.vivamarket.service.GoodsService;
import com.situ.vivamarket.service.OrderService;
import com.situ.vivamarket.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/api/v1/goods")
public class GoodsApi {
    private GoodsService goodsService;
    @Autowired
    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @GetMapping
    public ResponseEntity<JsonResult> list(GoodsSearchBean gsb,
                                           @RequestParam(defaultValue = "1") Integer page,
                                           @RequestParam (defaultValue = "10") Integer limit)
    {
        Page<?> p =new Page<>(page,limit);
        List<Goods> goods=goodsService.getAllGoods(gsb,p);
        PageInfo<Goods> pi=new PageInfo<>(goods);
        JsonResult result=JsonResult.successData(goods);
        result.setCount((int) pi.getTotal());
        return ResponseEntity.ok(result);
    }
//    删除商品
    @DeleteMapping
    public ResponseEntity<JsonResult> delete(Integer[] ids){
        if(ids.length==0){
            return ResponseEntity.noContent().build();
        }else{
//            必须确保订单里没有这个商品才能删,不用，item里存了
            int count=goodsService.deleteByIds(ids);
            if(count>0){
                return ResponseEntity.ok(JsonResult.successData(count));
            }else{
                return ResponseEntity.ok(JsonResult.fail("删除商品异常"));
            }
        }

    }
    @PostMapping
    public ResponseEntity<JsonResult> add(@Validated Goods goods){
        boolean success=goodsService.add(goods);
        if(success){
            return ResponseEntity.ok(JsonResult.successData(goods));
        }else{
            return ResponseEntity.internalServerError().body(JsonResult.fail("新增商品异常"));
        }
    }
    @GetMapping("/id")
    public ResponseEntity<JsonResult> findById(Integer id) {
        Goods goods = this.goodsService.findById(id);

        JsonResult result = JsonResult.successData(goods);
        return ResponseEntity.ok(result);
    }
    @PutMapping
    public ResponseEntity<JsonResult> update(@Validated Goods goods){
        boolean success=goodsService.update(goods);
        if(success){
            return ResponseEntity.ok(JsonResult.successData(goods));
        }else{
            return ResponseEntity.internalServerError().body(JsonResult.fail("修改商品异常"));
        }
    }
}
